
//
//  NRWCarHomeController.m
//  New_Runway
//
//  Created by mack on 2018/1/22.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarHomeController.h"
#import <SDCycleScrollView.h>
#import "NRWCarHomeTopCell.h"
#import "NRWCarPublicNoticeCell.h"
#import "NRWCarCarListCell.h"
#import "NRWCarHomeBannerModel.h"
#import "NRWCarHomeNoticeModel.h"
#import "NRWCarListsModel.h"
#import "CarDetailMainVC.h"
#import "BuyCarDetailVC.h"
#import "BannerDetailWebVc.h"
#import "CarSunscribeListVC.h"
#import "BuyCarMarketModel.h"
#import "NRWCarPublicNoticeController.h"
@interface NRWCarHomeController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (nonatomic,strong) SDCycleScrollView *bannerView;
@property (nonatomic, strong) NSMutableArray *iamgeDataArray;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *noticeArray;
@property (nonatomic, strong) NSMutableArray *carArray;
@property (nonatomic, strong) NRWCarHomeNoticeModel *notieModel;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, strong) NSMutableArray *subscribeArray;
@property (nonatomic, strong) BuyCarMarketModel *markerModel;

@end

@implementation NRWCarHomeController
-(NSMutableArray *)subscribeArray{
    if (!_subscribeArray) {
        _subscribeArray = [[NSMutableArray alloc] init];
    }
    
    return _subscribeArray;
}
-(NSMutableArray *)carArray{
    if (!_carArray) {
        _carArray = [[NSMutableArray alloc] init];
    }
    
    return _carArray;
}
-(NSMutableArray *)noticeArray{
    if (!_noticeArray) {
        _noticeArray = [[NSMutableArray alloc] init];
    }
    return _noticeArray;
}
-(NSMutableArray *)imageArr{
    if (!_imageArr) {
        _imageArr = [[NSMutableArray alloc] init];
    }
    return _imageArr;
}

-(NSMutableArray *)iamgeDataArray{
    if (!_iamgeDataArray) {
        _iamgeDataArray = [[NSMutableArray alloc] init];
    }
    return _iamgeDataArray;
}
-(NSMutableArray *)dataArray{
    if (_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MAIN_BACKGROUND_COLOR();
    self.navigationBarView.titleLabel.text = @"首页";
    self.navigationBarView.leftItem.hidden = YES;
    self.pageNo = 1;
    [self initTableview];
    [self loadAutoPicture];
    [self loadPublicNoticeData];
    [self loadMarketAdress];

    //    if ([NRWCarUser sharedUser].shopId) {
//        [self loadSubscribeCar];
//    }else{
//        
//        [self loadCarList];
//
//    }
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    if ([NRWCarUser sharedUser].shopId) {
        [self loadSubscribeCar];
    }else{
        
        [self loadCarList];
        
    }
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

}
#pragma mark 获取市场信息
-(void)loadMarketAdress{
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,allMarketListApi];
    NSDictionary *params = @{
                             @"marketId":[NRWCarUser sharedUser].marketId,
                             };
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            NSArray *array = response[@"result"];
            if (array.count != 0) {
                BuyCarMarketModel *model = [[BuyCarMarketModel alloc] init];
                [model setValuesForKeysWithDictionary:array[0]];
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:model.cityId forKey:KMarketAddressId];
                
            }
        }
        [self.tableview reloadData];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        
    }];
    
}
//-(void)updataVersion{
//    NSString *version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
//    NSDictionary *params = @{@"id":@"1352712474"};
//    NSString *appStoreurl = @"https://itunes.apple.com/lookup";
//    [YQNetworking postWithUrl:appStoreurl refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
//    } successBlock:^(id response) {
//        NSArray *array = response[@"results"];
//        if (array.count != 0) {// 先判断返回的数据是否为空   没上架的时候是空的
//            NSDictionary *dict = array[0];
//            NSString *versionStr = dict[@"version"];
//            self.url = response[@"results"][0][@"trackViewUrl"];
//
//            if ([versionStr floatValue] > [version floatValue]) {//判断版本大小了
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil] ;
//                alert.delegate = self;
//                [alert show];
//
//            }
//        }
//
//    } failBlock:^(NSError *error) {
//
//    }];
//
//}



-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarHomeTopCell" bundle:nil] forCellReuseIdentifier:@"NRWCarHomeTopCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarPublicNoticeCell" bundle:nil] forCellReuseIdentifier:@"NRWCarPublicNoticeCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarCarListCell" bundle:nil] forCellReuseIdentifier:@"NRWCarCarListCell"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
//    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(self.navH);
        make.bottom.equalTo(weakSelf.view).offset(-self.tabH);
        make.left.right.equalTo(weakSelf.view);
    }];

    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
        self.tableview.estimatedRowHeight = 0;
        self.tableview.estimatedSectionHeaderHeight = 0;
        self.tableview.estimatedSectionFooterHeight = 0;

    } else {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.automaticallyAdjustsScrollViewInsets=NO;
        
    }
    self.bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * 1 / 2) delegate:self placeholderImage:[UIImage imageNamed:@"banner"]];
    self.bannerView.currentPageDotImage = [UIImage imageWithColor:MAIN_NAV_COLOR() forSize:CGSizeMake(15, 2)];
    self.bannerView.pageDotImage = [UIImage imageWithColor:[UIColor whiteColor] forSize:CGSizeMake(15, 2)];
    self.tableview.tableHeaderView = self.bannerView;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 90;
    }else if (indexPath.section == 1){
        return 55;
    }
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 1;
    }else if (section == 2){
        return self.subscribeArray.count;

    }
    return self.carArray.count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        NRWCarHomeTopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarHomeTopCell"];
        cell.nav = self.navigationController;
        return cell;
    }else if (indexPath.section == 1){
        
        NRWCarPublicNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarPublicNoticeCell"];
        cell.notieModel = _notieModel;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    NRWCarCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarCarListCell"];
    cell.isBuyCar = YES;
    if (indexPath.section == 2) {
        cell.carModel = self.subscribeArray[indexPath.row];
    }else if (indexPath.section == 3){
        cell.carModel = self.carArray[indexPath.row];
    }
    
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] init];
    NSArray *array = @[@"订阅车源",@"推荐车源"];
    view.layer.masksToBounds = YES;
    if (section == 2 || section == 3) {
        view.backgroundColor = UIColorHex(0xf5f5f5);
        UIView *lineview = [[UIView alloc] init];
        lineview.backgroundColor = MAIN_NAV_COLOR();
        [view addSubview:lineview];
        [lineview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(view);
            make.width.mas_offset(2);
        }];
        UILabel *title = [[UILabel alloc] init];
        title.font = [UIFont systemFontOfSize:15];
        title.textColor = MAIN_FONT_COLOR();
        [view addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).mas_offset(16);
            make.top.bottom.equalTo(view);
        }];
        title.font = [UIFont systemFontOfSize:13];
        title.textColor = MAIN_FONT_COLOR();
        title.text = array[section -2];
        
        UIImageView *image =[[UIImageView alloc] init];
        image.image = [UIImage imageNamed:@"up"];
        [view addSubview:image];
        [image mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view).mas_offset(-16);
            make.centerY.equalTo(view);
        }];
        UIButton *btn = [[UIButton alloc] init];
        [btn setTitle:@"更多" forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [btn setTitleColor:UIColorHex(0x989898) forState:UIControlStateNormal];
        btn.tag = section;
        [view addSubview:btn];
        [btn addTarget:self action:@selector(LookMoreCar:) forControlEvents:UIControlEventTouchUpInside];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(image.mas_left).mas_offset(0);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(40);
            
        }];
    }
    return view;
}
-(void)LookMoreCar:(UIButton *)button{
    
    if (button.tag == 3) {
       [[NSNotificationCenter defaultCenter] postNotificationName:@"JUMP" object:[NSString stringWithFormat:@"%zd",1]userInfo:nil];

    }else if (button.tag == 2){
        CarSunscribeListVC *carlistvc = [[CarSunscribeListVC alloc] init];
        [self.navigationController pushViewController:carlistvc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2 || section == 3) {
        if (self.subscribeArray.count == 0) {
            if (section == 2) {
                return 0.001;
            }
        }
        return 30;
    }
    return 0.0001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (_notieModel) {
          
            NRWCarPublicNoticeController *noticeVc = [[NRWCarPublicNoticeController alloc] init];
            noticeVc.notieModel = _notieModel;
            [self.navigationController pushViewController:noticeVc animated:YES];
        }
       
    }else if (indexPath.section == 2){
        Result *rt = self.subscribeArray[indexPath.row];
        BuyCarDetailVC *detailVC = [[BuyCarDetailVC alloc] init];
        detailVC.carID = rt.carId;
        detailVC.carModel =rt;
        detailVC.isHistory = NO;
        [self.navigationController pushViewController:detailVC animated:YES];

    }else if (indexPath.section == 3){
        Result *rt = self.carArray[indexPath.row];
        BuyCarDetailVC *detailVC = [[BuyCarDetailVC alloc] init];
        detailVC.carModel =rt;
        detailVC.carID = rt.carId;
        detailVC.isHistory = NO;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }
    
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    NRWCarHomeBannerModel *model = self.iamgeDataArray[index];
    NSString *url = model.rotationUrl;
    if (isValidUrl(url) == YES) {
        BannerDetailWebVc *webVC = [[BannerDetailWebVc alloc] init];
        webVC.title = model.rotationName;
        webVC.url = url;
        [self.navigationController pushViewController:webVC animated:YES];
    }else{
        
        NSDictionary *dic = [self dictionaryWithJsonString:url];
        NSDictionary *iOSDic =dic[@"iOS"];
        NSString *classStr = iOSDic[@"path"];
        UIViewController *vcClass = [[NSClassFromString(classStr) alloc] init];
        [vcClass setValuesForKeysWithDictionary:iOSDic];
        if ([NRWCarUser sharedUser].shopId) {
            [self.navigationController pushViewController:vcClass animated:YES];
        }else{
            if ([classStr isEqualToString:@"CarWinAuctionVC"]) {
            }else{
                [self.navigationController pushViewController:vcClass animated:YES];
            }
        }
    }
   
}

-(void)downPullRefresh{
    self.pageNo = 1;
    [self loadAutoPicture];
    [self loadPublicNoticeData];
    
    if ([NRWCarUser sharedUser].shopId) {
        [self loadSubscribeCar];
    }else{
        
        [self loadCarList];
        
    }
    
}
-(void)upPullLoadMore{
    self.pageNo += 1;
//    [self loadCarList];
    
}

-(void)loadAutoPicture{
    NSDictionary *params = @{@"marketId":[NRWCarUser sharedUser].marketId,
                             @"rotationState":@"1"
                            
                             };
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,autoPictureApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [_imageArr removeAllObjects];
        [_iamgeDataArray removeAllObjects];
        NSArray *Array = response[@"result"];
        for (NSDictionary *dic in Array) {
            NRWCarHomeBannerModel *model = [[NRWCarHomeBannerModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            NSString *imageurl = [NSString stringWithFormat:@"%@%@",ImageApi,model.rotationImage];
            [self.imageArr addObject:imageurl];
            [self.iamgeDataArray addObject:model];
            
        }
        self.bannerView.imageURLStringsGroup = _imageArr;

        [self endRefresh];

    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

        [self endRefresh];
    }];

}

-(void)loadPublicNoticeData{
    
    NSDictionary *params = @{@"marketId":[NRWCarUser sharedUser].marketId,
                             };
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,publicNoticeApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        NSArray *noticeArr = response[@"result"];
        [self.noticeArray removeAllObjects];
        for (NSDictionary *dic in noticeArr) {
            NSDictionary *noticeDic =  dic[@"notice"];
            NRWCarHomeNoticeModel *notieModel = [[NRWCarHomeNoticeModel alloc] init];
            [notieModel setValuesForKeysWithDictionary:noticeDic];
            [self.noticeArray addObject:notieModel];
        }
        if (self.noticeArray.count != 0) {
            _notieModel = self.noticeArray[0];

        }

//        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        [self.tableview reloadData];
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];

    
}
//推荐
-(void)loadCarList{
    NSString *size;
    if (self.subscribeArray.count == 0) {
        size = @"10";
    }else{
        size = @"5";
    }
    
    NSDictionary *params = @{@"marketId":@(1),
                             @"pageIndex":@(self.pageNo),
                             @"pageSize":size,
                             @"carSaleState":@(20),
                             @"orderMode":@"DESC",
                             @"orderColunm":@"CAR_SALE_TIME"
                             };
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,carListsApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if (self.pageNo == 1) {
            [self.carArray removeAllObjects];
        }
        NSArray *noticeArr = response[@"result"];
        for (NSDictionary *dic in noticeArr) {
            Result *rt = [Result mj_objectWithKeyValues:dic];
            [self.carArray addObject:rt];
        }    
        [self.tableview reloadData];

        [self endRefresh];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [self endRefresh];

    }];
    
}
//订阅
-(void)loadSubscribeCar{
    NSDictionary *params = @{@"marketId":[NRWCarUser sharedUser].marketId,
                             @"shopId":[NRWCarUser sharedUser].shopId ?[NRWCarUser sharedUser].shopId : @"" ,
                             @"pageIndex":@(self.pageNo),
                             @"pageSize":@"5",
                             @"carSaleState":@(20)
                             };
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,subscribeCarLisrApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if (self.pageNo == 1) {
            [self.subscribeArray removeAllObjects];
        }
        NSArray *noticeArr = response[@"result"];
        for (NSDictionary *dic in noticeArr) {
            Result *rt = [Result mj_objectWithKeyValues:dic];
            [self.subscribeArray addObject:rt];
        }
        
        [self loadCarList];

//        [self.tableview reloadData];
//
//        [self endRefresh];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

        [self endRefresh];
        
    }];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}
-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
    
}
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(error) {
        NSLog(@"json解析失败：%@",error);
        return nil;
    }
    return dic;
}


@end
